package com.zcai.util.http;

/**
 * Created by zengcai on 2017/11/30.
 */
public class HttpClientHandler {

    /**
     * 发送请求Json格式
     *
     * @param params
     * @param actionUrl
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doPostJson(Map<String, String> params, String actionUrl)
            throws IOException
    {
        // 返回结果
        String result = null;
        // 请求参数
        Gson gs = new Gson();
        String jsonString = gs.toJson(params);
        logger.debug("HttpClient请求参数：" + jsonString);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try
        {
            //解决中文乱码问题
            StringEntity entity = new StringEntity(jsonString,"utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            HttpPost httpPost = new HttpPost(actionUrl);
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(40000).build();  //设置超时时间
            httpPost.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(httpPost);
            try
            {
                HttpEntity entitys = response.getEntity();
                if (response.getStatusLine().getReasonPhrase().equals("OK")
                        && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                {
                    result = EntityUtils.toString(entitys, "utf-8");
                    logger.debug("HttpClient返回结果：" + result);
                }
                EntityUtils.consume(entitys);
            }
            finally
            {
                httpPost.releaseConnection();
                response.close();
            }
        }
        finally
        {
            httpclient.close();
        }
        return result;
    }



    public static String doGet(Map<String, String> params, String url) throws Exception {
        log.debug("HttpGet请求参数:{}", params);
        String result = "";
        StringBuffer paramsStr = new StringBuffer();
        for (String key : params.keySet()) {
            paramsStr.append(key).append("=").append(params.get(key)).append("&");
        }
        if (paramsStr.length() > 1) {
            paramsStr.deleteCharAt(paramsStr.length() - 1);
        }
        HttpGet httpGet = new HttpGet(url.concat("?").concat(paramsStr.toString()));
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        result = EntityUtils.toString(entity, "UTF-8");
                        log.debug("result:{}", result);
                    }
                } else {
                    log.warn("HttpGet请求不成功,HttpStatus:{}", response.getStatusLine());
                }
            }
        }
        return result;
    }

}
